import React, { Component } from "react";
import Taro from "@tarojs/taro";
import { View, Text, Image, Input } from "@tarojs/components";
import "./index.less";
import { connect } from "react-redux";
import { AtInput, AtButton, AtAvatar } from "taro-ui";
import "taro-ui/dist/style/components/input.scss";
import "taro-ui/dist/style/components/icon.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/loading.scss";
import "taro-ui/dist/style/components/avatar.scss";
import md5 from "../../utils/md5js";

@connect(({ index }) => ({
  index
}))
export default class Login extends Component {
  state = {
    userName: "",
    passWord: "",
    loading: false
  };
  componentDidMount() {
    console.log(this.props);
  }

  goMain = () => {
    Taro.redirectTo({ url: "/pages/index/index?a=1&b=2&c=3" });
  };

  onSubmit = () => {
    const { userName, passWord } = this.state;
    if (!userName) {
      Taro.showToast({
        title: "用户名不能为空",
        icon: "none"
      });
      return;
    }
    if (!passWord) {
      Taro.showToast({
        title: "密码不能为空",
        icon: "none"
      });
      return;
    }
    console.log(userName, passWord);
    Taro.showLoading({ title: "登录中..." });
    this.props.dispatch({
      type: "index/login",
      payload: { userName, passWord: md5(passWord) },
      callback: result => {
        Taro.hideLoading();
        this.goMain();
      }
    });
  };

  changeValue = (value, key) => {
    let obj = {};
    obj[key] = value;
    this.setState(obj);
  };

  render() {
    const { userName, passWord } = this.state;
    return (
      <View className="login-page">
        <AtAvatar
          image="https://www.solosea.com/res/upload/fpdown/img/638c5a6143ec585c9bc6cbc612176a7d_thumb.jpg"
          className="login-icon"
        ></AtAvatar>
        <Text className="login-name">Demo</Text>
        <View className="login-form">
          <AtInput
            name="userName"
            title="用户名"
            value={userName}
            maxLength="40"
            onChange={(value, event) => this.changeValue(value, "userName")}
            type="text"
            placeholder="请输入用户名"
          ></AtInput>
          <AtInput
            name="passWord"
            title="密码"
            value={passWord}
            onChange={(value, event) => this.changeValue(value, "passWord")}
            maxLength="40"
            type="password"
            placeholder="请输入密码"
          ></AtInput>
        </View>

        <AtButton
          type="primary"
          size="normal"
          className="login-btn"
          onClick={this.onSubmit}
        >
          登录
        </AtButton>
      </View>
    );
  }
}
